import requests

def get_access_token(app_id, app_secret):
    url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={app_id}&secret={app_secret}&force_refresh=false"
    response = requests.get(url)
    # Check the response status code
    if response.status_code == 200:
        data = response.json()
        # Check if the 'access_token' key is in the data dictionary
        if 'access_token' in data:
            return data['access_token']
        else:
            print("'access_token' key not found in API response:", data)
            raise KeyError("'access_token' key not found in API response")
    else:
        print("API request failed with status code:", response.status_code)
        raise requests.exceptions.RequestException("API request failed")

def send_message(access_token, to_user, content):
    url = f"https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={access_token}"
    data = {
        "touser": to_user,
        "msgtype": "text",
        "text": {
            "content": content
        }
    }
    response = requests.post(url, json=data)
    return response.json()

def get_media_id(access_token, file_path, media_type):
    """
    上传临时素材到微信服务器
    :param access_token: 微信 Access Token
    :param file_path: 上传文件的本地路径
    :param media_type: 媒体文件类型（image, voice, video, thumb）
    :return: 微信服务器返回的 JSON 数据
    """
    url = f"https://api.weixin.qq.com/cgi-bin/media/upload?access_token={access_token}&type={media_type}"
    files = {"media": open(file_path, "rb")}
    
    response = requests.post(url, files=files)
    return response.json()['media_id']


if __name__ == '__main__':
    app_id = "wx51cb64ce8378743b"
    app_secret = "d36c9e32aafeae0794f99ce99905a48c"
    to_user = "o5182134821797120"
    content="hello"
    try:
        access_token = get_access_token(app_id, app_secret)
<<<<<<< HEAD
        media_id=get_media_id(access_token, 'images/1.png', 'image')
=======
        media_id=get_media_id(access_token, 'images/wx.gif', 'image')
>>>>>>> bdf8371a959fd6598c69d15d42752221fc9dd7ba
        print(media_id)
        print(access_token)
    except (KeyError, requests.exceptions.RequestException) as e:
        print("Error occurred while getting access token:", e)
